package org.ssssssss.magicapi.modules.spring;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;
import org.ssssssss.magicapi.core.annotation.MagicModule;
import org.ssssssss.script.annotation.Comment;

/**
 * env模块
 *
 * @author mxd
 */
@MagicModule("env")
public class EnvModule {

    private final Environment environment;

    public EnvModule(Environment environment) {
        this.environment = environment;
    }

    @Comment("获取配置")
    public String get(@Comment(name = "key", value = "配置项") String key) {
        return environment.getProperty(key);
    }

    @Comment("获取配置")
    public String get(@Comment(name = "key", value = "配置项") String key,
                      @Comment(name = "defaultValue", value = "未配置时的默认值") String defaultValue) {
        return environment.getProperty(key, defaultValue);
    }

    @Comment("获取配置")
    public Integer getInt(String key) {
        String value = environment.getProperty(key);
        return StringUtils.isNotBlank(value) ? Integer.parseInt(value.trim()) : null;
    }

    @Comment("获取配置")
    public Integer getInt(String key, Integer defaultValue) {
        String value = environment.getProperty(key);
        return StringUtils.isNotBlank(value) ? Integer.parseInt(value.trim()) : defaultValue;
    }

    @Comment("获取配置")
    public Long getLong(String key) {
        String value = environment.getProperty(key);
        return StringUtils.isNotBlank(value) ? Long.parseLong(value.trim()) : null;
    }

    @Comment("获取配置")
    public Long getLong(String key, Long defaultValue) {
        String value = environment.getProperty(key);
        return StringUtils.isNotBlank(value) ? Long.parseLong(value.trim()) : defaultValue;
    }

    @Comment("获取配置")
    public Boolean getBoolean(String key) {
        String value = environment.getProperty(key);
        if (StringUtils.isNotBlank(value)) {
            value = value.toLowerCase().trim();
            if ("true".equals(value)) {
                return true;
            } else if ("false".equals(value)) {
                return false;
            }
            throw new RuntimeException("The value can not parse to Boolean : " + value);
        }
        return false;
    }

    @Comment("获取配置")
    public Boolean getBoolean(String key, Boolean defaultValue) {
        String value = environment.getProperty(key);
        if (StringUtils.isNotBlank(value)) {
            value = value.toLowerCase().trim();
            if ("true".equals(value)) {
                return true;
            } else if ("false".equals(value)) {
                return false;
            }
            throw new RuntimeException("The value can not parse to Boolean : " + value);
        }
        return defaultValue;
    }
}
